<template>
  <div class="system-edit-menu-container">
    <el-dialog
        draggable
        :title="state.editType === 'save'? '新增组织' : '修改组织'"
        v-model="state.isShowDialog"
        width="769px">
      <el-form :model="state.form" :rules="state.rules" ref="departmentFormRef" size="default" label-width="80px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="上级组织" prop="parent_id">
              <el-tree-select
                  ref="departmentTreeRef"
                  filterable
                  v-model="state.form.parent_id"
                  :data="departmentTreeData"
                  :props="{label: 'name', value: 'id',children:'children'}"
                  check-strictly
                  :render-after-expand="false"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="组织名称" prop="title">
              <el-input v-model="state.form.name" placeholder="格式：message.router.xxx" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="组织类型" prop="type">
              <el-input v-model="state.form.type" placeholder="路由中的 name 值" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="state.form.remarks" placeholder="备注" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="saveOrUpdate">保 存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EditDepartment">
import {computed, nextTick, onMounted, reactive, ref} from 'vue';
import {ElMessage} from "element-plus";
import {departmentApi} from "/@/api/hrms/department"

const departmentTreeRef = ref()
const departmentFormRef = ref()

const emit = defineEmits(['getDepartmentList'])
const props = defineProps({
  allDepartmentTreeList: {
    type: Array,
    default: () => []
  },
  departmentList: {
    type: Array,
    default: () => []
  }
})

// 平铺
const departmentListData = computed(() => {
  return [{name: '根目录', id: -99, children: [...props.departmentList]}]
})

// 树结构
const departmentTreeData = computed(() => {
  return [{name: '根目录2', id:null, children: [...props.allDepartmentTreeList]}]
})

const createForm = () => {
  return {
    id: null, // 上级组织
    name: null, // 部门名称
    parent_id: null, // 上级组织id
    parent_name: null, // 上级组织名称
    type: null, // 类型
    department_route: null, // 路由路径
    remarks: ''
  }
}

const state = reactive({
  isShowDialog: false,
  editType: '',
  // 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由组织格式
  form: createForm(),
  rules: {
    name: [{required: true, message: '请输入组织名称', trigger: 'blur'},],
    // parent_id: [{required: true, message: '请选择上级组织', trigger: 'blur'},]
  },
  menuData: [], // 上级组织数据
});

// 打开弹窗
const openDialog = (editType, row) => {
  state.editType = editType
  if (row) {
    state.form = JSON.parse(JSON.stringify(row));
  } else {
    state.form = createForm()
  }
  state.isShowDialog = true;
  nextTick(() => {
    departmentTreeRef.value.setCurrentKey(state.form.parent_id)
  })
};
// 关闭弹窗
const closeDialog = () => {
  state.isShowDialog = false;
};

const onCancel = () => {
  closeDialog();
};
// 新增
// const saveOrUpdate = async () => {
//   await departmentApi().departmentSave(state.form)
//       .then(() => {
//         ElMessage.success('操作成功');
//         emit('getDepartmentList')
//         console.log('重新刷新列表成功:')
//         closeDialog(); // 关闭弹窗
//       })
// };
const saveOrUpdate = async () => {
  departmentFormRef.value.validate(async (valid) => {
    if (valid) {
      if (state.editType === 'save' || state.editType === 'update') {
        await departmentApi().departmentSave(state.form)
        ElMessage.success('操作成功');
        emit('getDepartmentList')
        console.log('11111111111111111')
        closeDialog(); // 关闭弹窗
      }
    }
  })
};

// 页面加载时
onMounted(() => {
  // getMenuData();
});


defineExpose({
  openDialog,
})

</script>
